// 设置localStorage过期时间
const expires = new Date().getTime() + 1000 * 60 * 60 * 24;

export const getItem = <T>(key: string) => {
  const data = window.localStorage.getItem(key)
  if (!data) return null
  try {
    const item = JSON.parse(data)
    if (item.expires && new Date().getTime() > item.expires) {
      localStorage.removeItem(key); // 过期则删除
    } else {
      return item.data as T
    }
  } catch (err) {
    return null
  }
}

export const setItem = (key: string, value: object | string | null) => {
  if (typeof value === 'object') {
    const item = {
      data: value,
      expires: expires
    };
    value = JSON.stringify(item)
  }
  window.localStorage.setItem(key, value)
}

export const removeItem = (key: string) => {
  window.localStorage.removeItem(key)
}
